﻿using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

namespace Learning
{
    public class MiscRenderPass2 : ScriptableRenderPass
    {
        public MiscSetting setting;

        private RenderTexture _rtTex;
        
        public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
        {
        }

        public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
        {
            ConfigureClear(ClearFlag.All, Color.clear);
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (setting.material_2 == null)
            {
                return;
            }
            
            RenderTextureDescriptor rt = new RenderTextureDescriptor(Camera.main.pixelWidth, Camera.main.pixelHeight, RenderTextureFormat.Default, 0);
            _rtTex = RenderTexture.GetTemporary(rt);

            RenderTargetIdentifier cameraColorTexture = renderingData.cameraData.renderer.cameraColorTarget;

            CommandBuffer cmd = CommandBufferPool.Get(name: "MiscRenderPass2");

            cmd.Blit(cameraColorTexture, _rtTex, setting.material_2);
            cmd.Blit(_rtTex, cameraColorTexture);

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();
            CommandBufferPool.Release(cmd);
        }

        public override void OnCameraCleanup(CommandBuffer cmd)
        {
            if (_rtTex != null) {
                RenderTexture.ReleaseTemporary(_rtTex); // 需要显示的释放，否则会出现奔溃
                _rtTex = null;
            }
        }
    }
}
